# -*- coding: utf-8 -*-

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <icatalan@opendomo.com>



"""
Constants and helper functions for access to Opendomo CGI
"""
from elisa.core.utils.i18n import install_translation
from elisa.core.media_uri import MediaUri
from elisa.core.default_config import CONFIG_DIR
from elisa.core.utils import defer
from elisa.plugins.poblesec.modal_popup import Popup

import time
from datetime import datetime

from elisa.plugins.base.models.image import ImageModel

try:
    from hashlib import md5
except ImportError:
    # hashlib is new in Python 2.5
    from md5 import md5

from xml.dom import minidom
import os
import ConfigParser
_ = install_translation('poblesec')
CONFIG_FILE='/etc/opendomo/od-moovida-plugin.conf'
"""
We retrieve the agent's URL
"""
config = ConfigParser.RawConfigParser()
config.read(CONFIG_FILE)
AGENT_IP=config.get('CGI Agent', 'IP')
USER=config.get('CGI Agent', 'USER')
PWD=config.get('CGI Agent', 'PWD')
#AGENT_IP='plugins.moovida.com'
URL_ROOT='/cgi-bin/od.cgi'
#URL_ROOT='/plugin_list?elisa_version=1.0.9'
BASE_API_URI = 'http://'+AGENT_IP+URL_ROOT
XML_TAIL = 'GUI=XML'
#XML_ACTIVE = ''
COOKIE_JAR='/tmp/marbudorada'

""" 
Diferent of types of opendomo's cgi output, 
TODO: Should the CGI return this codes instead of
finding them out parsing the xml fields? 
"""
MENU_ITEM=1
COMMAND=2
SCRIPT=3
CAMERA_LIST=4
CAMERA_SHOW=5

LOGGED_IN=False
TOKEN_LEN=41

def message_box(self, title_, label):
	"""
	Display an alert widget to inform that the model is empty.

	@param label: the text of the alert
	@type label:  C{unicode}
	"""
	if self._empty_alert_widget is not None:
		# There is already an empty alert displayed.
		return

	def go_back():
		browser = self.frontend.retrieve_controllers('/poblesec/browser')[0]
		browser.history.go_back()

	title = title_
	subtitle = label
	text = ''
	buttons = [(_('Back'), go_back)] 

	self._empty_alert_widget = Popup(title, subtitle, text, buttons)
	self._empty_alert_widget.set_name('empty_alert')
	self._empty_alert_widget.visible = True
	self.widget.add(self._empty_alert_widget)
	self.widget.set_focus_proxy(self._empty_alert_widget)
	if self.widget.focus:
		self._empty_alert_widget.set_focus()


def get_cached_token():
    str_auth = ''
    if os.path.exists(COOKIE_JAR):
       contents=file(COOKIE_JAR).read().replace('#','').replace('\n','').strip()
       if contents.find('HTSESSID') == -1:
          return str_auth
       else:
          str_auth='HTSESSID='+contents.split('HTSESSID=')[1].split(';')[0].strip()
          LOGGED_IN=True   
    return str_auth

def getUrl2Param(url, param):

    url_tmp = '' 
    
    if len(param) < 1:
       return url
       
    if url.find('?') == -1:
       url_tmp = url + '?' + param
    else:
       url_tmp = url + '&' + param
    
    return url_tmp
    

def isDir(url):
    f_index = url.find('FILE')
    if f_index != -1:
          return False
    else:
          print 'IS DIR'
          return True

def isImage(url):
    if url.find('.jpg') != -1 or url.find('.png') != -1 or url.find('.gif') != -1:
       print 'IS IMAGE'    
       return True
    else:
       return False

def isScript(url):
    if (url.find('.sh') != -1 and "browseCaptures" not in url and "browseFiles" not in url) \
       or "﻿config?GUI=XML" in url or "﻿control?GUI=XML" in url or "﻿sec?GUI=XML" in url or \
       "﻿tools?GUI=XML" in url:
       print 'IS SCRIPT'        
       return True
    else:
       return False

def isVideo(url):
    if url.find('.swf') != -1 or url.find('.avi') != -1 or url.find('.mpg') != -1 \
       or url.find('.mpeg') != -1 or url.find('.wmv') != -1 or url.find('.mov') != -1:
       print 'IS video'               
       return True
    else:
       return False
       
def isCamera(url):
    if AGENT_IP+':80' in url:
       return True
    else:
       return False
       
def getTokenizedUrl(url):

    url_tmp = url
    index = url_tmp.find('HTSESSID=')
    cookie_sid = get_cached_token()
    if isVideo(url):
       if index == -1:
          url_tmp = getUrl2Param(url_tmp, cookie_sid)
       else:
           # check for valid auth token from the cookie
           url_sid=url[index:index+TOKEN_LEN]
           if url_sid != cookie_sid:
              url_tmp=url.replace(url_sid,cookie_sid)

    if url_tmp.find('GUI=') == -1:
       url_tmp = getUrl2Param(url_tmp, XML_TAIL)

    return url_tmp

    
def check_token():
    if os.path.exists(COOKIE_JAR):
       contents=file(COOKIE_JAR).read()
       if contents.find(';') == -1:
          return False
       str_expire_date=contents.split(';')[4].split('=')[1].replace('"','').replace('Z','').strip()
       if datetime.strptime(str_expire_date, '%Y-%m-%d %H:%M:%S') > datetime.now():
          return True
       else:
          return False
    else:
         return False
    
def get_token_file():

	return "test"

def get_login_url(provider):
    def get_url():
        login = generate_call_uri(BASE_API_URI)
        return defer.succeed({'url': login})

    request_defer = get_url()
    return request_defer

def generate_call_uri(base_uri=BASE_API_URI, method=None, arguments={},
                      authenticated=False, sign=False):
    full_arguments = arguments.copy()

    argvalues = [key + '=' + value for key, value in full_arguments.items()]
    uri = base_uri + '&'.join(argvalues)
    return uri
